import "./index.css";

const animation = {
    show_and_down_animation: "show-and-down-animation",
    disapper: "disapper",
    show: "show",
}
let view = document.querySelector(".contain");
view.style.minHeight = "" + window.innerHeight + "px";
window.onresize = () => {
    //view.style.height = "" + window.innerHeight + "px";
    if (window.innerHeight < 500) {
        //MyClassName.addClassName(document.querySelector(".circle-wrapper"), "hide");
    } else {
        // MyClassName.removeClassName(document.querySelector(".circle-wrapper"), "hide");
    }
}
window.onload = () => {
    getNameAndClass((req) => {
        document.querySelector("#name").value = req.name;
        document.querySelector("#class").value = req.class;
    })
    MyEvent.clickGroup(EventCallBack.changeGroup);
    //MyEvent.animationEnd(EventCallBack.nextPage);
    //MyEvent.clickNext(EventCallBack.startAnimation);
    MyEvent.timeChange(EventCallBack.timeChange);
    MyEvent.inputChange(EventCallBack.completed);
    MyEvent.clickSubmit(EventCallBack.submit);
    MyEvent.inputFocus(EventCallBack.inputFocus);
    MyEvent.inputBlur(EventCallBack.inputBlur);

    //MyEvent.clickTime();
    //textShow();
}

function textShow() {
    let text = document.querySelector(".head-text");
    MyClassName.addClassName(text, animation.show_and_down_animation);
}

class MyClassName {
    static addClassName(ele, className) {
        let arr = ele.className.split(" ");
        arr.push(className);
        let newClassName = arr.join(" ");
        ele.className = newClassName;
    }

    static removeClassName(ele, className) {
        let arr = ele.className.split(" ");
        for (let i = 0; i < arr.length; i++) {
            if (arr[i] === className) {
                arr.splice(i, 1);
            }
        }
        let newClassName = arr.join(" ");
        ele.className = newClassName;
    }

    static modClassName(ele, old, newClass) {
        let arr = ele.className.split(" ");
        for (let i = 0; i < arr.length; i++) {
            if (arr[i] === old) {
                arr[i] = newClass;
            }
        }
        let newClassName = arr.join(" ");
        ele.className = newClassName;
    }

}

function getNameAndClass(callBack) {

    // ajax

    MyAjax.ajax({
        type: "GET",
        data: {},
        url: "http://121.4.127.126:3000/api/mob/query-applicant-result",
        before: (xhr) => {
            xhr.setRequestHeader("token", localStorage.getItem("token"));
        },
        success: (xhr) => {
            let data = JSON.parse(xhr.responseText);
            if (!data.status) {
                let res = {
                    name: data.result.name,
                    class: data.result.class
                }
                callBack(res);
            } else if (data.status === 1) {
                alert("当前用户未登录");
                window.location = "/";
            }
        },
        err: (xhr) => {
            console.log(xhr.status);
        }
    });
}


class MyEvent {
    static inputFocus(callBack) {
        let inputs = document.querySelectorAll(".input-box>input,#why");
        for (let i = 0; i < inputs.length; i++) {
            inputs[i].addEventListener("focus", (e) => {
                e.stopPropagation();
                callBack(inputs[i]);
            })
        }
    }

    static inputBlur(callBack) {
        let inputs = document.querySelectorAll(".input-box>input, #why");
        for (let i = 0; i < inputs.length; i++) {
            inputs[i].addEventListener("blur", (e) => {
                e.stopPropagation();
                callBack(inputs[i]);
            })
        }
    }

    static animationEnd(callBack /*Function*/ ) {
        let disEles = document.querySelector(".contain");
        disEles.addEventListener("animationend", (e) => {
            e.stopPropagation();
            callBack(disEles);
        });
    }

    static clickNext(callBack) {
        document.querySelector("#next").addEventListener("click", (e) => {
            e.stopPropagation();
            callBack();
        })
    }

    static clickGroup(callBack) {
            let groups = document.querySelectorAll(".group-radio>label");
            for (let i = 0; i < groups.length; i++) {
                groups[i].addEventListener("click", (e) => {
                    e.stopPropagation();
                    callBack(groups, i);
                });
            }
        }
        // 废弃
    static clickTime(callBack) {
        let lab = document.querySelector("label.act-btn");
        let time = document.querySelector("#time");
        lab.addEventListener("click", (e) => {
            //time.style.opacity = "1";
        })
    }

    static timeChange(callBack) {
        time.addEventListener("change", (e) => {
            e.stopPropagation();
            callBack();
        })
    }

    static inputChange(callBack) {
        let inputs = document.querySelectorAll(".input-box>input");
        for (let i = 0; i < inputs.length; i++) {
            if (inputs[i].name === "why") {
                continue;
            } else if (inputs[i].name === "qq") {
                inputs[i].addEventListener("change", (e) => {
                    e.stopPropagation();
                    if (EventCallBack.checkMail(inputs[i].value)) {
                        EventCallBack.completed(inputs[i]);
                        inputs[i].parentElement.classList.add("input-bd");
                        inputs[i].parentElement.classList.remove("bd-focus");
                        inputs[i].parentElement.classList.remove("bd-err");
                        MyClassName.addClassName(document.querySelector("#err"), "invisible");
                    } else {
                        inputs[i].parentElement.classList.remove("input-bd");
                        inputs[i].parentElement.classList.remove("bd-focus");
                        inputs[i].parentElement.classList.add("bd-err")
                        MyClassName.removeClassName(document.querySelector("#err"), "invisible");
                    }
                })
            } else if(inputs[i].id === "phone") {
                inputs[i].addEventListener("change", (e) => {
                    e.stopPropagation();
                    if(EventCallBack.checkPhone(inputs[i].value)) {
                        EventCallBack.completed(inputs[i]);
                        inputs[i].parentElement.classList.add("input-bd");
                        inputs[i].parentElement.classList.remove("bd-focus");
                        inputs[i].parentElement.classList.remove("bd-err");
                    } else {
                        inputs[i].parentElement.classList.remove("input-bd");
                        inputs[i].parentElement.classList.remove("bd-focus");
                        inputs[i].parentElement.classList.add("bd-err")
                    }
                })
            } else {
                inputs[i].addEventListener("change", (e) => {
                    e.stopPropagation();
                    callBack(inputs[i]);
                })
            }
        }

        let select = document.querySelector("select");
        select.addEventListener("change", (e) => {
            e.stopPropagation();
            if (select.value) {
                MyClassName.addClassName(select.parentElement.parentElement.children[0].children[0], "hide");
            } else {
                MyClassName.removeClassName(select.parentElement.parentElement.children[0].children[0], "hide");
            }
        })
    }

    static clickSubmit(callBack) {
        let submit = document.querySelector("#submit");
        submit.addEventListener("click", (e) => {
            e.stopPropagation();
            callBack();
        })
    }
}

class EventCallBack {
    static inputBlur(input) {
        if (input.value && input.name != "qq" && input.id != "phone") {
            MyClassName.removeClassName(input.parentElement, "bd-focus");
            MyClassName.addClassName(input.parentElement, "input-bd");

        } else if (input.name != "qq" && input.name != "why" && input.id != "phone") {
            MyClassName.removeClassName(input.parentElement, "bd-focus");
            MyClassName.addClassName(input.parentElement, "bd-err");
        } else if (input.name === "why") {
            MyClassName.removeClassName(input.parentElement, "bd-focus");
            MyClassName.addClassName(input.parentElement, "input-bd");
        } else if (EventCallBack.checkMail(input.value) && input.id != "phone") {
            MyClassName.removeClassName(input.parentElement, "bd-focus");
            MyClassName.addClassName(input.parentElement, "input-bd");
        } else if (EventCallBack.checkPhone(input.value)) {
            MyClassName.removeClassName(input.parentElement, "bd-focus");
            MyClassName.addClassName(input.parentElement, "input-bd");
        } else {
            MyClassName.removeClassName(input.parentElement, "bd-focus");
            MyClassName.addClassName(input.parentElement, "bd-err");
        }
    }

    static inputFocus(input) {
        input.parentElement.classList.remove("bd-err");
        input.parentElement.classList.remove("input-bd");
        MyClassName.addClassName(input.parentElement, "bd-focus");
    }

    static nextPage(disEles) {
        let page1 = document.querySelector("#page-1");
        let page2 = document.querySelector("#page-2");
        if (page1.className.split(" ").indexOf("hide")) {
            MyClassName.addClassName(page1, "hide");
        }
        document.querySelector(".head-text").innerHTML = "加入我们";
        MyClassName.removeClassName(page2, "hide");
        MyClassName.modClassName(disEles, "disapper", animation.show);
    }

    static startAnimation() {
        let disEles = document.querySelector(".contain");
        MyClassName.addClassName(disEles, animation.disapper);
    }

    static changeGroup(groups, i) {
        for (let j = 0; j < groups.length; j++) {
            let className = groups[j].className;
            let classList = className.split(" ");
            let group = classList[classList.length - 1].split("-")[1];
            let old = "bg-" + group;
            MyClassName.removeClassName(groups[j], old);
        }
        // document.querySelector(".time-input-box").classList.add("hide");
        let className = groups[i].className;
        let classList = className.split(" ");
        let group = classList[classList.length - 1].split("-")[1];
        let newClassName = "bg-" + group;
        let time = document.querySelector("#time");
        let chooseTime = document.querySelector(".time-input-box>.text-box>.text");
        chooseTime.innerHTML = "查询可选时间...";
        time.style.pointerEvents = "none";
        MyClassName.addClassName(groups[i], newClassName);
        MyAjax.ajax({
            url: "http://121.4.127.126:3000/api/mob/query-number-of-people",
            type: "GET",
            data: {
                group: document.querySelector("#" + groups[i].htmlFor).value,
            },
            before: function(xhr) {
                xhr.setRequestHeader("token", localStorage.getItem("token"));
            },
            success: function(xhr) {
                let data = JSON.parse(xhr.responseText);
                if(!data.status) {
                    let options = document.querySelectorAll("option");
                    for(let k = 0; k < options.length; k++) {
                        if(options[k].value != "null") {
                            document.querySelector("#time").removeChild(options[k]);
                        }
                    }
                    let labtext = document.querySelector(".time-input-box>.text-box>.text");
                    time.style.pointerEvents = "all";
                    labtext.innerHTML = "选择时间";
                    document.querySelector("#select-hide-input").value = "";
                    for(let k = 0; k < data.result.length; k++) {
                        let op = document.createElement("option");
                        op.code = "" + data.result[k].code;
                        op.innerHTML = "" + data.result[k].timeString;
                        op.value = "" + data.result[k].timeString + "&" + data.result[k].code;
                        document.querySelector("#time").appendChild(op);
                    }
                    document.querySelector(".time-input-box").classList.remove("hide");
                } else {
                    time.style.pointerEvents = "all";
                    chooseTime.innerHTML = "选择时间";
                    alert("服务器错误");
                    // document.querySelector(".time-input-box").classList.remove("hide");
                }
            },
            err: (xhr) => {
                time.style.pointerEvents = "all";
                chooseTime.innerHTML = "选择时间";
                alert("请求失败");
                // document.querySelector(".time-input-box").classList.remove("hide");
            }
        })
    }

    static timeChange() {
        let time = document.querySelector("#time");
        let labtext = document.querySelector(".time-input-box>.text-box>.text");
        let input = document.querySelector("#select-hide-input");
        labtext.innerHTML = time.value.split("&")[0];
        input.value = time.value.split("&")[1];
    }

    static completed(input) {
        if (input.value) {
            MyClassName.addClassName(input.parentElement.children[0].children[0], "hide");
        } else {
            MyClassName.removeClassName(input.parentElement.children[0].children[0], "hide");
        }
    }

    static submit() {
        //未实现
        let data = GetData.getAllFormData();
        console.log(data);
        if (checkForm(data)) {
            //提交
            MyAjax.ajax({
                url: "http://121.4.127.126:3000/api/mob/apply",
                type: "POST",
                data: data,
                dataType: "json",
                before: (xhr) => {
                    xhr.setRequestHeader("token", localStorage.getItem("token"));
                },
                success: (xhr) => {
                    if (!JSON.parse(xhr.responseText).status) {
                        alert("报名成功")
                        window.location = "./result.html";
                    } else {
                        alert(JSON.parse(xhr.responseText).msg);
                    }
                },
                err: (xhr) => {
                    alert("报名失败")
                }
            })
        } else {
            alert("您的表单未完成");
        }
    }

    static checkMail(str) {
        let ePattern = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        if (ePattern.test(str)) {
            return true;
        } else {
            return false;
        }
    }

    static checkPhone(str) {
        let p = /^[1]([3-9])[0-9]{9}$/;
        if(p.test(str)) {
            return true;
        } else {
            return false;
        }
    }
}

class GetData {
    // 未实现
    static getAllFormData() {
        let form = document.querySelector("form");
        let formData = {
            name: form.name.value,
            class: form.class.value,
            tel: form.tel.value,
            qq: form.qq.value,
            group: form.group.value,
            time: form.time[0].value,
            why: form.why.value
        }

        return formData;
    }
}

class MyAjax {
    static ajax(act) {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
                    act.success(xhr);
                } else {
                    act.err(xhr);
                }
            }
        }
        if (act.type == 'GET') {
            let each;
            for (each in act.data) {
                act.url += act.url.indexOf('?') == -1 ? "?" : "&";
                act.url = act.url + encodeURIComponent(each) + "=" + encodeURIComponent(act.data[each]);
            }
            xhr.open(act.type, act.url, true);
            if (act.before) {
                act.before(xhr);
            }
            xhr.send();
        } else if (act.type === 'POST' && act.dataType === "json") {

            xhr.open(act.type, act.url, true);
            if (act.before) {
                act.before(xhr);
            }
            xhr.setRequestHeader("Content-Type", "application/json");
            xhr.send(JSON.stringify(act.data));
        } else {
            xhr.open(act.type, act.url, true);
            if (act.before) {
                act.before(xhr);
            }
            console.log(act.data);
            xhr.send(act.data);
        }

    }
}

function checkForm(data) {
    if (data.name && data.class &&
        EventCallBack.checkPhone(data.tel) && EventCallBack.checkMail(data.qq) &&
        data.group && data.time) {
        return true;
    } else {
        return false
    }
}